package org.jeecg.modules.chg.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.arc.entity.ArcAccount;
import org.jeecg.modules.arc.entity.BasePeriod;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.arc.service.IBasePeriodService;
import org.jeecg.modules.chg.entity.ChgPayments;
import org.jeecg.modules.chg.entity.ChgStatement;
import org.jeecg.modules.chg.entity.ChgStoreds;
import org.jeecg.modules.chg.entity.ChgSubPayments;
import org.jeecg.modules.chg.mapper.ChgPaymentsMapper;
import org.jeecg.modules.chg.mapper.ChgSubPaymentsMapper;
import org.jeecg.modules.chg.service.IChgFeesService;
import org.jeecg.modules.chg.service.IChgPaymentsService;
import org.jeecg.modules.chg.service.IChgStatementService;
import org.jeecg.modules.chg.service.IChgStoredsService;
import org.jeecg.modules.chg.vo.ChgPaymentsCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 缴费记录
 * @Author: jeecg-boot
 * @Date:   2022-02-21
 * @Version: V1.0
 */
@Service
public class ChgPaymentsServiceImpl extends ServiceImpl<ChgPaymentsMapper, ChgPayments> implements IChgPaymentsService {

	@Autowired
	private ChgPaymentsMapper chgPaymentsMapper;
	@Autowired
	private ChgSubPaymentsMapper chgSubPaymentsMapper;
	@Autowired
	private IChgFeesService chgFeesService;
	@Autowired
	private IChgStoredsService storedsService;
	@Autowired
	private IArcAccountService arcAccountService;
	@Autowired
	private IBasePeriodService basePeriodService;

	@Autowired
	private IChgStatementService chgStatementService;

	@Override
	public IPage<ChgPayments> cancelPageList(Page<ChgPayments> page, ChgPayments query) {
		return chgPaymentsMapper.cancelPageList(page,query);
	}

	@Override
	@Transactional
	public void saveMain(ChgPayments chgPayments, List<ChgSubPayments> chgSubPaymentsList) {
		chgPaymentsMapper.insert(chgPayments);
		if(chgSubPaymentsList!=null && chgSubPaymentsList.size()>0) {
			for(ChgSubPayments entity:chgSubPaymentsList) {
				//外键设置
				entity.setPaymentId(chgPayments.getId());
				chgSubPaymentsMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(ChgPayments chgPayments,List<ChgSubPayments> chgSubPaymentsList) {
		chgPaymentsMapper.updateById(chgPayments);

		//1.先删除子表数据
		chgSubPaymentsMapper.deleteByMainId(chgPayments.getId());

		//2.子表数据重新插入
		if(chgSubPaymentsList!=null && chgSubPaymentsList.size()>0) {
			for(ChgSubPayments entity:chgSubPaymentsList) {
				//外键设置
				entity.setPaymentId(chgPayments.getId());
				chgSubPaymentsMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		chgSubPaymentsMapper.deleteByMainId(id);
		chgPaymentsMapper.deleteFlagId(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			chgSubPaymentsMapper.deleteByMainId(id.toString());
			this.chgPaymentsMapper.deleteFlagId(id.toString());
		}
	}

	@Override
	public List<ChgPayments> selectBillNoOpen(String accCode, String createTimeBegin, String createTimeEnd) {
		return chgPaymentsMapper.selectBillNoOpen(accCode,createTimeBegin,createTimeEnd);
	}

	/**查询预支付状态订单*/
	@Override
	public List<ChgPayments>selectPrePayOrder(String prepayId,  String status){
		return chgPaymentsMapper.selectPrePayOrder(prepayId,status);
	}

	/**收费实缴分类汇总-按天按收费员*/
	@Override
	public List<ChgPaymentsCountVo> chargePaymentsCount(String beginDate, String endDate){
		return chgPaymentsMapper.chargePaymentsCount(beginDate,endDate);
	}

	@Override
	@Transactional
	public Result<?> cancelPay(ChgPayments chgPayments) {
		ArcAccount arcAccount = arcAccountService.getById(chgPayments.getAccountId());
		BasePeriod basePeriod = basePeriodService.getOne(
				new LambdaQueryWrapper<BasePeriod>().eq(BasePeriod::getIsUsed, 1));

		ChgPayments payments = chgPaymentsMapper.selectById(chgPayments.getId());
		//账户余额
		BigDecimal balance = arcAccount.getBalance();
		if(null != payments && 1 != payments.getStatus()){
			throw new JeecgBootException("该笔缴费不是成功状态");
		}

		if (basePeriod.getMonth().equals(payments.getFinancialMonth())) {

			//预存记录无效
			storedsService.update(new LambdaUpdateWrapper<ChgStoreds>()
							.set(ChgStoreds::getStatus,2) //取消
							.eq(ChgStoreds::getFeeStruckStatus, "1") //冲红状态是被冲帐
							.eq(ChgStoreds::getPaymentId, payments.getId())
							.eq(ChgStoreds::getDelFlag, 0)
							.eq(ChgStoreds::getStatus, "1")
//						.eq(ChgStoreds::getFeeTargetType, "1")// 缴费类型 是1扣费的
			);

			balance=balance.subtract(payments.getPayFee().subtract(payments.getZeroFee()));

			//缴费记录无效
			payments.setStatus(2);
			payments.setRemark("取消充值");
			chgPaymentsMapper.updateById(payments);

			/**设置首页数据动态更新-退费*/
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						chgFeesService.indexData(null,null);
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						log.warn("首页数据动态更新");
					}
				}
			}).start();

			/**.缴费账户余额变化*/
			arcAccountService.update(new LambdaUpdateWrapper<ArcAccount>()
					.set(ArcAccount::getBalance, balance)
					.eq(ArcAccount::getId, arcAccount.getId()));
			return Result.OK("取消充值成功");

		}else{
			throw new JeecgBootException("不允许跨月取消");
		}
	}

	@Override
	public void inportBillByAbc() {

		String outPath="D:/wwwroot/bill/abc"+ DateUtils.getDate("yyyyMMdd")+".CVS";
		List<String> strings = FileUtil.readLines(new File(outPath), "utf-8");
		String code="2c9fd081843c789401843c7894500000";
		for (String lines : strings) {
			System.out.println(lines);
			if( null != lines && lines.length()>2
					&& ! lines.startsWith("|交易日期")
					&& ! lines.startsWith("|103881350003391")
					&& ! lines.startsWith("|商户号")){
				String[] items = lines.split(",");

				System.out.println(items);
				ChgStatement statement = new ChgStatement();
				statement.setBillJyrq(items[0].replace("|",""));
				statement.setBillJysj(items[1].replace("|",""));
				statement.setBillJfzxlsh(items[3].replace("|",""));


				JSONObject jsonObj = new JSONObject();

				statement.setBillZfddh(items[4].replace("|",""));
				statement.setBillJylsh(items[5].replace("|",""));
				statement.setBillShzdh(items[6].replace("|",""));
				statement.setBillJfxmbh(items[7].replace("|",""));
				statement.setBillShdm(items[9].replace("|",""));
				statement.setBillShmc(items[10].replace("|",""));

				statement.setBillYhid(items[11].replace("|",""));
				statement.setBillZfje(new BigDecimal(items[12].replace("|","")));
				statement.setBillYhje(new BigDecimal(items[13].replace("|","")));
				statement.setBillJfzt( items[14].replace("|",""));
				statement.setBillJfyhsr1(items[15].replace("|",""));

				statement.setBillJfyhsr2( items[16].replace("|",""));
				statement.setBillJfyhsr3(items[17].replace("|",""));
				statement.setBillSkshh(items[20].replace("|",""));

				statement.setBillJfqd( items[24].replace("|",""));
				statement.setBillTklsh( items[25].replace("|",""));
				statement.setBillTkddh( items[26].replace("|",""));
				statement.setBillTkje( new BigDecimal(items[27].replace("|","")));
				statement.setBillTkzt( items[29].replace("|",""));
				statement.setBillQsms(items[30].replace("|",""));

				statement.setBillSfbs(items[33].replace("|",""));

				chgStatementService.save(statement);

				/**
				 * |交易日期,
				 * 1|交易时间,|会计日期,|缴费中心流水号,|商E付支付订单号,|主机交易流水号,
				 * 6|缴费商户账单号,|缴费项目编号,|缴费项目名称,|商户代码,|商户名称,
				 * 11|用户ID,|支付金额,|优惠金额,|缴费状态,|缴费用户输入1,
				 * 16|缴费用户输入2,|缴费用户输入3,|缴费用户输入4,|缴费用户输入5,|收款商户号,
				 * 21|收款账号,|分账模板号,|付款账号,|缴费渠道,|缴费中心退款流水号,
				 * 26|商E付退款订单号,|缴费退款金额,|优惠退款金额,|缴费退款状态,|清算模式,
				 * 31|套餐编码,|套餐名称,|收付标识
				 `bill_jyrq` varchar(255) DEFAULT NULL COMMENT '交易日期',
				 `bill_jysj` varchar(255) DEFAULT NULL COMMENT '交易时间',
				 `bill_jfzxlsh` varchar(255) DEFAULT NULL COMMENT '缴费中心流水号',
				 `bill_zfddh` varchar(255) DEFAULT NULL COMMENT '支付订单号',
				 `bill_jylsh` varchar(255) DEFAULT NULL COMMENT '交易流水号',
				 `bill_shzdh` varchar(255) DEFAULT NULL COMMENT '商户账单号',
				 `bill_jfxmbh` varchar(255) DEFAULT NULL COMMENT '项目编号',
				 `bill_shdm` varchar(255) DEFAULT NULL COMMENT '商户代码',
				 `bill_shmc` varchar(255) DEFAULT NULL COMMENT '商户名称',
				 `bill_yhid` varchar(255) DEFAULT NULL COMMENT '用户ID',
				 `bill_zfje` decimal(10,2) DEFAULT NULL COMMENT '支付金额',
				 `bill_yhje` decimal(6,2) DEFAULT NULL COMMENT '优惠金额',
				 `bill_jfzt` varchar(255) DEFAULT NULL COMMENT '缴费状态',
				 `bill_jfyhsr1` varchar(255) DEFAULT NULL COMMENT '缴费账号',
				 `bill_jfyhsr2` varchar(255) DEFAULT NULL COMMENT '缴费用户输入2',
				 `bill_jfyhsr3` varchar(255) DEFAULT NULL COMMENT '缴费用户输入3',
				 `bill_skshh` varchar(255) DEFAULT NULL COMMENT '收款商户号',

				 `bill_jfqd` varchar(255) DEFAULT NULL COMMENT '缴费渠道',
				 `bill_tklsh` varchar(255) DEFAULT NULL COMMENT '退款流水号',
				 `bill_tkddh` varchar(255) DEFAULT NULL COMMENT '退款订单号',
				 `bill_tkje` decimal(10,2) DEFAULT NULL COMMENT '退款金额',
				 `bill_tkzt` varchar(255) DEFAULT NULL COMMENT '退款状态',
				 `bill_qsms` varchar(255) DEFAULT NULL COMMENT '清算模式',
				 `bill_sfbs` varchar(255) DEFAULT NULL COMMENT '收付标识',
				 `CREATE_BY` varchar(32) DEFAULT NULL COMMENT '创建人',
				 `CREATE_TIME` datetime DEFAULT NULL COMMENT '创建时间',
				 `del_flag` int(1) DEFAULT '0' COMMENT '是否删除',
				 `tenant_id` int(4) DEFAULT NULL COMMENT '租户网点',
                 */
				//baseAPI.createOnlineData(code, jsonObj);
				}
			}
			//JSONObject jsonObj = new JSONObject();
			//jsonObj.put("cus_id", arcCustomers.getId());
			//jsonObj.put("cus_code", arcCustomers.getCode());
			//jsonObj.put("cus_name", arcCustomers.getCusName());
			//jsonObj.put("old_text", arcCustomers.getNatureId());
			//jsonObj.put("new_text", materObj.getString("natureId"));
	}
}
